package com.example.librarymanagementproject2.Common.aop;

import com.example.librarymanagementproject2.Common.config.RabbitConfig;
import com.example.librarymanagementproject2.Common.exception.GlobalException;
import com.example.librarymanagementproject2.model.dto.UserRegisterDTO;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @ClassName LoginAspect
 * @Description TODO
 * @Author Kx
 * @Date 2025/10/22 19:58
 * @Version 1.0
 */
@Aspect
@Component
public class LoginAspect {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * @author: kx
     * @date: 2025/10/22 20:04
     * @param joinPoint : 切入点
     * @description: 用户注册后置通知
    */
    @AfterReturning(value = "execution(* com.example.librarymanagementproject2.service.impl.LoginServiceImpl.addUser(..))")
    public void addUser(JoinPoint joinPoint) {
        try {
            // 获取方法参数
            Object[] args = joinPoint.getArgs();

            // 转换为UserRegisterDTO对象
            UserRegisterDTO userRegisterDTO = (UserRegisterDTO) args[0];
            // 创建消息唯一ID
            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            // 投递消息
            rabbitTemplate.convertAndSend(RabbitConfig.USER_EXCHANGE, RabbitConfig.USER_LOGIN_ROUTING_KEY, userRegisterDTO.getUser(), correlationData);
        } catch (Exception e) {
            throw new GlobalException(500, "用户文档信息添加失败" + e.getMessage());
        }
    }
}
